package com.icinfo.cloud.provider.punish.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.dto.TransferConfigureQueryDto;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.service.ITaskCenterService;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.vo.EvidenceConfigVo;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.vo.TransferConfigureVo;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.api.dto.*;
import com.icinfo.cloud.provider.punish.api.service.ICaseSourceInfoShareService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceRegisterCheckContentSaveDto;
import com.icinfo.cloud.provider.punish.csource.manage.dto.FlowCommonDto;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceMaterialRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterDetailInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.*;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceFlowRecordService;
import com.icinfo.cloud.provider.punish.evideinv.dto.QueryEvidencePageDto;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.evideinv.vo.EvidencePageNewVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 描述：案源信息接口实现类
 *
 * @Author zhengqiang
 * @Date 2022/8/20 15:44
 **/
@Slf4j
@Service
public class CaseSourceInfoShareServiceImpl implements ICaseSourceInfoShareService {

    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;
    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;
    @Resource
    private ITaskCenterService taskCenterService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private CaseSourceMaterialRecordMapper caseSourceMaterialRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseSourceFlowRecordService caseSourceFlowRecordService;


    /**
     * 【V1.4.1】描述： 查询案源移送信息
     *
     * @author: zhengqiang
     * @date: 2022/8/23
     * @param: caseSourceId
     * @return {@link TransferCaseDTO}
     **/
    @Override
    public TransferCaseDTO getTransferCaseSourceInfo(String caseSourceId) {
        TransferCaseDTO transferCaseDTO = new TransferCaseDTO();
        //查询案源主表
        CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);
        if (ObjectUtils.isEmpty(mainInfo)) {
            throw new BusinessException("案源信息不存在; caseSourceId:" + caseSourceId);
        }

        //联络人
        List<TransferCaseAgentDTO> agentList = new ArrayList<>();
        //查询检查信息表
        CaseSourceRegisterDetailInfo detailInfo = caseSourceRegisterDetailInfoMapper.selectByPrimaryKey(caseSourceId);
        if (ObjectUtils.isEmpty(detailInfo)) {
            transferCaseDTO.setIsRelationTask(YesOrNoEnum.NO.getCode());
            //查看指派人员信息
            if (!ObjectUtils.isEmpty(mainInfo.getHandlePersonMainId())){
                TransferCaseAgentDTO caseAgentMain = new TransferCaseAgentDTO();
                caseAgentMain.setUserId(mainInfo.getHandlePersonMainId());
                caseAgentMain.setUserName(mainInfo.getHandlePersonMainName());
                caseAgentMain.setPhone(xzzfInterfaceService.getUserPhoneByUserId(mainInfo.getHandlePersonMainId()));
                //1-任务带出的检查人员 2-手动添加
                caseAgentMain.setUserType(Constant.STRING_2);
                agentList.add(caseAgentMain);
            }

            if (!ObjectUtils.isEmpty(mainInfo.getHandlePersonAssistId())){
                TransferCaseAgentDTO caseAgentAssist = new TransferCaseAgentDTO();
                caseAgentAssist.setUserId(mainInfo.getHandlePersonAssistId());
                caseAgentAssist.setUserName(mainInfo.getHandlePersonAssistName());
                //设置手机号
                caseAgentAssist.setPhone(xzzfInterfaceService.getUserPhoneByUserId(mainInfo.getHandlePersonAssistId()));
                //1-任务带出的检查人员 2-手动添加
                caseAgentAssist.setUserType(Constant.STRING_2);
                agentList.add(caseAgentAssist);
            }

        } else {
            transferCaseDTO.setIsRelationTask(YesOrNoEnum.YES.getCode());
            transferCaseDTO.setTaskCode(detailInfo.getCheckTaskNumber());
            transferCaseDTO.setTaskId(detailInfo.getCheckTaskId());
            transferCaseDTO.setTaskName(detailInfo.getCheckTaskName());
            transferCaseDTO.setCheckEntId(detailInfo.getCheckEntId());
            transferCaseDTO.setCheckOrgId(detailInfo.getCheckOrgId());

            //异常点
            List<TransferCasePointDTO> pointList = new ArrayList<>();
            List<CaseSourceRegisterCheckContentSaveDto> checkPositionContentList =
                    JSON.parseArray(detailInfo.getCheckPositionContent(), CaseSourceRegisterCheckContentSaveDto.class);
            checkPositionContentList.forEach(e -> {
                TransferCasePointDTO pointDTO = new TransferCasePointDTO();
                pointDTO.setPointContent(e.getCheckPositionName());
                pointDTO.setCheckPointId(e.getCheckPointId());
                pointDTO.setCheckFormId(e.getCheckFormId());
                pointDTO.setPointId(e.getPointId());
                pointList.add(pointDTO);
            });
            transferCaseDTO.setPointList(pointList);

            //获取检查人员信息
            TransferCaseAgentDTO caseAgentMain = new TransferCaseAgentDTO();
            caseAgentMain.setUserId(detailInfo.getCheckMainPersonId());
            caseAgentMain.setUserName(detailInfo.getCheckMainPersonName());
            caseAgentMain.setPhone(xzzfInterfaceService.getUserPhoneByUserId(detailInfo.getCheckMainPersonId()));
            //1-任务带出的检查人员 2-手动添加
            caseAgentMain.setUserType(Constant.STRING_1);


            TransferCaseAgentDTO caseAgentAssist = new TransferCaseAgentDTO();
            caseAgentAssist.setUserId(detailInfo.getCheckAssistPersonId());
            caseAgentAssist.setUserName(detailInfo.getCheckAssistPersonName());
            caseAgentAssist.setPhone(xzzfInterfaceService.getUserPhoneByUserId(detailInfo.getCheckAssistPersonId()));
            //1-任务带出的检查人员 2-手动添加
            caseAgentAssist.setUserType(Constant.STRING_1);

            agentList = Arrays.asList(caseAgentMain, caseAgentAssist);
        }
        //设置联络人
        transferCaseDTO.setAgentList(agentList);

        //主体
        Example partyExample=new Example(CaseSourcePartyInfo.class);
        partyExample.createCriteria().andEqualTo("caseSourceId", caseSourceId).andEqualTo("status",Constant.STRING_1);
        List<CaseSourcePartyInfo> caseSourcePartyInfos=caseSourcePartyInfoMapper.selectByExample(partyExample);
        if (!ObjectUtils.isEmpty(caseSourcePartyInfos)) {
            CaseSourcePartyInfo caseSourcePartyInfo = caseSourcePartyInfos.get(0);
            transferCaseDTO.setLegalEntityCode(caseSourcePartyInfo.getPartyIdentityCode());
            transferCaseDTO.setLegalEntityName(caseSourcePartyInfo.getPartyName());
            transferCaseDTO.setLegalEntityType(ObjectUtils.isEmpty(caseSourcePartyInfo.getLegalEntityType()) ? caseSourcePartyInfo.getPartyType() : caseSourcePartyInfo.getLegalEntityType());
            transferCaseDTO.setLegalEntityId(ObjectUtils.isEmpty(caseSourcePartyInfo.getLegalEntityId()) ? caseSourcePartyInfo.getId() : caseSourcePartyInfo.getLegalEntityId());
            String address = caseSourcePartyInfo.getAddressDetail();
            if (!ObjectUtils.isEmpty(caseSourcePartyInfo.getAddressAreas())) {
                address = caseSourcePartyInfo.getAddressAreas().replace(",", "") + caseSourcePartyInfo.getAddressDetail();
            }
            transferCaseDTO.setDom(address);
        }

        //处罚事项
        String listCode = "";
        Example example=new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseSourceId).andEqualTo("status","1");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
            CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(0);
            listCode = caseReasonMainRecord.getCaseReasonCode();
            transferCaseDTO.setTransferListCode(listCode);
            transferCaseDTO.setTransferListName(caseReasonMainRecord.getCaseReasonName());
        }


        //移交材料配置
        //查询本地证据
        Example updateExample = new Example(CaseSourceMaterialRecord.class);
        updateExample.createCriteria().andEqualTo("caseSourceId", caseSourceId).andEqualTo("isDelete", Constant.STRING_0);
        List<CaseSourceMaterialRecord> caseSourceMaterialRecords = caseSourceMaterialRecordMapper.selectByExample(updateExample);

        List<TransferCaseEvidenceDTO> evidenceList = new ArrayList<>();
        TransferConfigureQueryDto queryDto = new TransferConfigureQueryDto();
        queryDto.setListCode(listCode);
        TransferConfigureVo configureVo = taskCenterService.getTransferCaseEvidenceBy(queryDto);
        if (ObjectUtils.isEmpty(configureVo)) {
            throw new BusinessException("获取证据材料列表异常");
        }
        transferCaseDTO.setTransferUid(configureVo.getTransferUid());
        transferCaseDTO.setTransferName(configureVo.getTransferName());
        List<EvidenceConfigVo> evidenceConfigList = configureVo.getEvidenceList();
        for (EvidenceConfigVo evidenceConfigVo : evidenceConfigList) {
            TransferCaseEvidenceDTO transferCaseEvidenceDTO = new TransferCaseEvidenceDTO();
            BeanUtils.copyProperties(evidenceConfigVo, transferCaseEvidenceDTO);
            //返回证据附件列表
            List<TransferCaseEvidenceAnnexDTO> annexList = new ArrayList<>();
            if (!ObjectUtils.isEmpty(caseSourceMaterialRecords)) {
                for (CaseSourceMaterialRecord materialRecord : caseSourceMaterialRecords) {
                    if (evidenceConfigVo.getEvidenceCode().equals(materialRecord.getEvidenceCode())
                            || (evidenceConfigVo.getEvidenceCode().equals("OTHER") && ObjectUtils.isEmpty(materialRecord.getEvidenceCode()))) {
                        //没有对应协同证据分类的都放在其他证据下
                        TransferCaseEvidenceAnnexDTO annexDTO = new TransferCaseEvidenceAnnexDTO();
                        annexDTO.setFileName(materialRecord.getMaterialName());
                        //判断是否证据中心附件
                        if (ObjectUtils.isEmpty(materialRecord.getEvidenceUid())) {
                            //来源类型：1 执法平台OSS附件 2完整路径附件 3证据中心
                            annexDTO.setFileSourceType(Constant.STRING_2);
                            annexDTO.setFilePath(materialRecord.getMaterialUrl());
                        } else {
                            //来源类型：1 执法平台OSS附件 2完整路径附件 3证据中心
                            annexDTO.setFileSourceType(Constant.STRING_3);
                            //filePath：对应证据中心的标识UID
                            //fileSuffix：对应证据中心的linkType
                            annexDTO.setFilePath(materialRecord.getEvidenceUid());
                            annexDTO.setFileSuffix(materialRecord.getEvidenceLinkType());
                        }
                        //附件来源 ：1 案件上传 2 处罚 3检查
                        annexDTO.setFileSource(Constant.STRING_2);
                        annexList.add(annexDTO);
                    }
                }

            }

            if ("OTHER".equals(evidenceConfigVo.getEvidenceCode())) {
                //查询证据库证据
                QueryEvidencePageDto dto = new QueryEvidencePageDto();
                dto.setBusinessType(Constant.STRING_1);
                dto.setCaseId(caseSourceId);
                dto.setPageNum(1);
                dto.setPageSize(1000);
                PageResponse<EvidencePageNewVo> evidencePage = evidenceInventoryService.getEvidencePage(dto);
                if (!ObjectUtils.isEmpty(evidencePage.getData())) {
                    List<EvidencePageNewVo> data = evidencePage.getData();
                    data.forEach(e -> {
                        TransferCaseEvidenceAnnexDTO annexDTO = new TransferCaseEvidenceAnnexDTO();
                        annexDTO.setFileName(e.getEvidenceName());
                        //来源类型：1 执法平台OSS附件 2完整路径附件 3证据中心
                        annexDTO.setFileSourceType(Constant.STRING_3);
                        //filePath：对应证据中心的标识UID
                        //fileSuffix：对应证据中心的linkType
                        annexDTO.setFilePath(e.getUid());
                        annexDTO.setFileSuffix(e.getLinkType());
                        //附件来源 ：1 案件上传 2 处罚 3检查
                        annexDTO.setFileSource(Constant.STRING_2);
                        annexList.add(annexDTO);
                    });
                }
            }

            transferCaseEvidenceDTO.setAnnexList(annexList);
            evidenceList.add(transferCaseEvidenceDTO);
        }
        transferCaseDTO.setEvidenceList(evidenceList);


        //创建人
        transferCaseDTO.setCreateUserId(mainInfo.getCreateUserId());
        transferCaseDTO.setCreateUser(mainInfo.getCreateUserName());
        transferCaseDTO.setCreateOrgCode(mainInfo.getCreateUserOrgCode());
        transferCaseDTO.setCreateOrgName(mainInfo.getCreateUserOrgName());
        transferCaseDTO.setCreateTime(mainInfo.getCreateTime());

        //处罚移送默认配置
        //移交的状态 1待移送（暂存） 2移送中（待接收）3、已接收 4、已退回
        transferCaseDTO.setTransferStatus(Constant.STRING_1);
        //1-认领处罚事项的部门 2-全部部门勾选的
        transferCaseDTO.setTransferOrgType(Constant.STRING_1);
        //来源类型 默认0 案件移送  1检查 2处罚
        transferCaseDTO.setSourceType(Constant.STRING_2);
        transferCaseDTO.setSourceRelId(caseSourceId);
        transferCaseDTO.setSourceName(mainInfo.getCaseSourceName());
        transferCaseDTO.setSourceStatus(mainInfo.getCaseSourceStatus());
        transferCaseDTO.setSourceStatusName(CaseSourceStatusEnum.getValue(mainInfo.getCaseSourceStatus()));


        return transferCaseDTO;
    }

    /**
     * 描述： 保存案源移送结果
     *
     * @author: zhengqiang
     * @date: 2022/8/28
     * @param: caseSourceId
     * @return {@link Result}
     **/
    @Override
    public Result saveTransferResultById(String caseSourceId) {
        //查询案源主表
        CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);
        if (ObjectUtils.isEmpty(mainInfo)) {
            throw new BusinessException("案源信息不存在; caseSourceId:" + caseSourceId);
        }
        mainInfo.setCaseSourceStatus(CaseSourceStatusEnum.TRANSFER.getIndex());
        mainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYYS);
        int i = caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(mainInfo);
        //保存流转记录
        saveCaseSourceFlowRecord(caseSourceId);
        //调用协同接口告知已移送
        /*TripartiteStatusDto statusDto = new TripartiteStatusDto();
        statusDto.setRelUid(caseSourceId);
        statusDto.setRelStatus(CaseSourceStatusEnum.TRANSFER.getIndex());
        statusDto.setRelStatusName(CaseSourceStatusEnum.TRANSFER.getName());
        Result result = taskCenterService.tripartiteStatusByRelUid(statusDto);
        log.info(" 修改协同的案件移送状态(协同)返回结果:{}", result);*/
        if (i > 0) {
            return Result.success(Constant.STRING_SUCCESS_EN);
        }
        return Result.success(Constant.STRING_FAIL_CH);
    }

    /**
     * 流转日志保存
     *
     * @param caseSourceId
     */
    private void saveCaseSourceFlowRecord(String caseSourceId){
        //流转日志保存 案源立案
        CaseSourceFlowRecord lastCaseSourceFlowRecord = caseSourceFlowRecordService.getLastCaseSourceFlowRecord(caseSourceId);
        if (!ObjectUtils.isEmpty(lastCaseSourceFlowRecord) && !ObjectUtils.isEmpty(lastCaseSourceFlowRecord.getCaseSourceId())) {
            if (Constant.CASE_SOURCE_STAGE_AYYS.equals(lastCaseSourceFlowRecord.getFlowStageType())) {
                return;
            }
        }
        UserDTO userDTO= UserUtil.getUserInfo();
        FlowCommonDto dto=new FlowCommonDto();
        dto.setCaseSourceId(caseSourceId);
        dto.setFlowStartTime(new Date());
        dto.setFlowEndTime(new Date());
        dto.setStartPersonName(userDTO.getRealName());
        dto.setStartPersonOrgName(userDTO.getOrgName());
        dto.setStartPersonDeptName(userDTO.getDeptName());
        dto.setFlowStageType(Constant.CASE_SOURCE_STAGE_AYYS);
        caseSourceFlowRecordService.saveCommonFlowRecord(dto);
    }

}
